﻿package com.dispatcher.http;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.dispatcher.ActivityBase;
import com.dispatcher.R;
import com.dispatcher.common.CommonDefine;
import com.zuzhili.database.CacheDataCtrl;
import com.zuzhili.database.SDCardAccessor;

class HttpThread extends Thread {
	private int timeoutConnection = 30000;
	private int timeoutSocket = 30000;
	private BasicHttpParams httpParameters;
	HttpHelperWraper http;
	List<HttpHelperWraper.HttpRequestParam> mreqparams = new ArrayList<HttpHelperWraper.HttpRequestParam>();
	byte[] mlock = new byte[0];

	public HttpThread() {
		httpParameters = new BasicHttpParams();
		httpParameters.setParameter("http.protocol.version",HttpVersion.HTTP_1_0);
		HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection);
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
		http = new HttpHelperWraper();
		start();
	}

	public void postRequest(HttpHelperWraper.HttpRequestParam param) {
		synchronized (mlock) {
			if (param.task.equals("getMatchList")
					|| param.task.equals("getMatchListDif")) {

				for (HttpHelperWraper.HttpRequestParam item : mreqparams) {
					if (item.task.equals(param.task)) {
						return;
					}
				}
			}
			mreqparams.add(param);
		}
		Message msg = new Message();
		msg.obj = param;
		if (mHandler == null) {
			try {
				sleep(300);
			} catch (InterruptedException e) {

			}
		}
		mHandler.sendMessage(msg);
	}

	public Handler mHandler = null;

	@Override
	public void run() {
		Looper.prepare();

		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				HttpClient clienttemp = new DefaultHttpClient(httpParameters);
				HttpHelperWraper.HttpRequestParam param = (HttpHelperWraper.HttpRequestParam) msg.obj;
				do {
					boolean b = http.executeTask(param, clienttemp);
					if (b) {
						synchronized (mlock) {
							mreqparams.remove(param);
						}
						break;
					}
					try {

						sleep(3000);
					} catch (Exception e) {

					}
				} while (true);

				super.handleMessage(msg);
			}
		};

		Looper.loop();

	}
}

public class HttpHelperWraper {
	static BasicHttpParams httpParameters;
	static BasicHttpParams httpLongTimeParameters;
	public static final String BOUNDARY = "7cd4a6d158c";
	public static final String MP_BOUNDARY = "--" + BOUNDARY;
	public static final String END_MP_BOUNDARY = "--" + BOUNDARY + "--";
	public static final String MULTIPART_FORM_DATA = "multipart/form-data";
	static private HttpThread mThread = new HttpThread();

	public static void init(Context ctx) {

		int timeoutConnection = 30000;
		int timeoutSocket = 30000;
		int timeoutSocketLong = 60000;
		if (httpParameters == null) {

			httpParameters = new BasicHttpParams();
			httpParameters.setParameter("http.protocol.version",
					HttpVersion.HTTP_1_0);
		}
		if (httpLongTimeParameters == null) {

			httpLongTimeParameters = new BasicHttpParams();
			httpLongTimeParameters.setParameter("http.protocol.version",
					HttpVersion.HTTP_1_0);
		}
		HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection);
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

		HttpConnectionParams.setConnectionTimeout(httpLongTimeParameters,
				timeoutConnection);
		HttpConnectionParams.setSoTimeout(httpLongTimeParameters,
				timeoutSocketLong);

		// Create and initialize HTTP parameters
		// HttpParams params = new BasicHttpParams();
		// ConnManagerParams.setMaxTotalConnections(httpParameters, 100);
		// HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);

		// Create and initialize scheme registry
		// SchemeRegistry schemeRegistry = new SchemeRegistry();
		// schemeRegistry.register(
		// new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

		// Create an HttpClient with the ThreadSafeClientConnManager.
		// This connection manager must be used if more than one thread will
		// be using the HttpClient.
		// ClientConnectionManager cm = new
		// ThreadSafeClientConnManager(httpParameters, schemeRegistry);
		// httpclient = new DefaultHttpClient(cm, httpParameters);

		// getHostUrl(ctx);
	}

	public interface OnNetListener {
		public void onNetSuccess(HttpRequestParam param);

		public void onNetError(HttpRequestParam param);
	}

	public class HttpRequestParam {
		public String username;
		public Context ctx;
		public Object activitybase;
		public String url;
		public String task;
		public Map<String, Object> nodesrequest;
		public OnNetListener listener;
		public String rstmsg;
		public JSONObject nodesresult;
		public String jsonstr;
		public long ltimestamp;
//		public Map<String, ByteArrayOutputStream> attatchfiles;
		public Map<String, Object> attatchfiles;
		public Map<String, String> attatchfiles_uri;
		public Map<String, String> draftdisplayinfo;
		public Map<String, ByteArrayOutputStream> binaryfiles;

		public int cachetype = -1;
		public String identify;
		public boolean bendreq = false;
		public boolean bcachedata = false;
		public boolean bnetdata = false;
		public int expiretime=300000;
		public long latestTime;
		public String type;
		public String flag;
	}

	private DownloadListener mDownloadListener;

	public interface DownloadListener {
		public void onDownloadBegin(int total);

		public void onDownloadUpdateProgress(int cur);

		public void onDownloadEnd(String file);
	}

	public InputStream is = null;
	// static String hosturl;
	// public String url = "http://mylucky.oicp.net/trunk/mobile/index.php";

	public String url = "mobile/index.php";
	public String ret_from_net = null;
	final static String Pattern_Xml_Result = "json#jinghao(.+)";
	final static String Pattern_Normal_Result = "errmsg#jinghao(.+)";

	public static Pattern mpattern_xml = Pattern.compile(Pattern_Xml_Result,
			Pattern.DOTALL);
	public static Pattern mpattern_err = Pattern.compile(Pattern_Normal_Result,
			Pattern.DOTALL);

	private static final int NET_CONNECT = 1;
	private static final int NET_COMPLETE = 2;
	private static final int NET_ERROR = 3;
	private static final int NET_UPDATE = 4;

	private static final int DOWN_BEGIN = 11;
	private static final int DOWN_UPDATE_PROGRESS = 12;
	private static final int DOWN_END = 13;

	EventHandler mHandler = new EventHandler();

	public static String HostUrl = "";
	// public Context ctx = null;

	private String mRequestTask;

	public String getRequestTask() {
		return mRequestTask;
	}

	public HttpRequestParam getParam() {
		return new HttpRequestParam();
	}

	public static void releaseParamMemory(HttpRequestParam param) {
		if (param.attatchfiles != null) {
			Iterator it = param.attatchfiles.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry entry = (Map.Entry) it.next();
				try {
					ByteArrayOutputStream bos = (ByteArrayOutputStream) entry
							.getValue();
					try {
						bos.close();
					} catch (IOException e) {

					}

				} catch (ClassCastException e) {

				}
			}
		}
	}

	public static String getHostUrl(Context ctx) {
		String url = "http://aiwowo.just521.com/mobile/index.php";
//		String url = "http://192.168.40.25/aiwowo/mobile/index.php";
		return url;
	}

	public void setUrl(String url_str) {
		url = url_str;
	}

	public boolean checknetworkstatus() {
		return true;
	}

	public boolean SyncTask(HttpRequestParam param) {
		HttpClient clienttemp = new DefaultHttpClient(httpParameters);
		return executeTask(param, clienttemp);
	}

	public boolean SyncTaskSyncRst(HttpRequestParam param) {
		HttpClient clienttemp = new DefaultHttpClient(httpParameters);
		return executeTaskSyncRst(param, clienttemp);
	}

	public void AsyncTask(HttpRequestParam param) {
		final HttpRequestParam paramt = param;
		new Thread(new Runnable() {
			@Override
			public void run() {
				BasicHttpParams hp = null;
//				if (paramt.task.equals("publish_file.json")
//						|| paramt.task.equals("publish_pic.json")) {
//					hp = httpLongTimeParameters;
//				} else {
					hp = httpParameters;
//				}
				HttpClient clienttemp = new DefaultHttpClient(httpParameters);
				executeTask(paramt, clienttemp);
			}
		}).start();
	}

	public void AsyncTaskWithCache(HttpRequestParam param) {
		final HttpRequestParam paramt = param;
		new Thread(new Runnable() {
			@Override
			public void run() {
				BasicHttpParams hp = null;
//				if (paramt.task.equals("publish_file.json")
//						|| paramt.task.equals("publish_pic.json")) {
//					hp = httpLongTimeParameters;
//				} else {
					hp = httpParameters;
//				}
				HttpClient clienttemp = new DefaultHttpClient(httpParameters);
				boolean b = cacheTask(paramt);
				if (!b) {

					executeTask(paramt, clienttemp);
				}
			}
		}).start();
	}

	public void AsyncTaskWithCache(HttpRequestParam param, final long delay) {
		final HttpRequestParam paramt = param;
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Thread.sleep(delay);
				} catch (InterruptedException e) {

				}
				BasicHttpParams hp = null;
				if (paramt.task.equals("publish_file.json")
						|| paramt.task.equals("publish_pic.json")) {
					hp = httpLongTimeParameters;
				} else {
					hp = httpParameters;
				}
				HttpClient clienttemp = new DefaultHttpClient(httpParameters);
				boolean b = cacheTask(paramt);
				if (!b) {

					executeTask(paramt, clienttemp);
				}
			}
		}).start();
	}

	public void LinearAsyncTask(HttpRequestParam param) {
		mThread.postRequest(param);
	}

	public boolean executeTaskSyncRst(HttpRequestParam param, HttpClient client) {
		return executeTaskInternal(param, client, true);
	}

	public boolean executeTask(HttpRequestParam param, HttpClient client) {
		return executeTaskInternal(param, client, false);
	}

	public boolean executeTaskInternal(HttpRequestParam param,
			HttpClient client, boolean bissyncrst) {
		String value = "";
		boolean bRet = false;
		String temp_task = param.task;
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// params.add(new BasicNameValuePair("task", temp_task));
		addParamsPost(params, param.nodesrequest);
		String ret_from_net = null;
		do {
			HostUrl = getHostUrl(param.ctx);
			HttpPost httpRequest = new HttpPost(HostUrl);
			Log.e("liutao", "url:" + HostUrl + temp_task);

			HttpResponse httpResponse = null;
			try {
				MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE);
				uploadTextParam(params, entity);
				if (param.attatchfiles != null && param.attatchfiles.size()>0) {
					uploadAttatchFileParam(param.attatchfiles, entity);
					httpRequest.setEntity(entity); 
				} else if(param.binaryfiles != null && param.binaryfiles.size() > 0){
					uploadBinaryFileParam(param.binaryfiles, entity);
					httpRequest.setEntity(entity); 
				} else {
					HttpEntity httpentity = new UrlEncodedFormEntity(params,
							"utf-8");
					httpRequest.setEntity(httpentity);
				}
				httpRequest.setHeader("Connection", "close");
				NetworkControl.NetType netType = NetworkControl
						.getNetType(param.ctx);
				if (netType != null && netType.isWap()) {
					HttpHost proxy = new HttpHost(netType.getProxy(),
							netType.getPort());
					client.getParams().setParameter(
							ConnRoutePNames.DEFAULT_PROXY, proxy);
				}
				httpResponse = client.execute(httpRequest);
				int code = httpResponse.getStatusLine().getStatusCode();
				Log.d("debug", "net status code:" + code);
				// int code = 200;
				if (code == HttpStatus.SC_OK) {
					JSONObject ob = null;
					String retBuf = null;
					retBuf = EntityUtils.toString(httpResponse.getEntity(),
							"utf-8");
					value = retBuf;
					Log.d("task:"+param.task+" return json value", "reVal:"+retBuf);
					try {

						ob = new JSONObject(retBuf);
						String y = null;
						if(param.flag != null && param.flag.equals("form")) {
							y = ob.getString("msg");
						} else {
							y = ob.getString("errmsg");
						}
						if (y.equals("ok") || y.equals("success")) {
							bRet = true;

							param.nodesresult = ob;
							param.jsonstr = retBuf;
							if (bissyncrst) {
								param.listener.onNetSuccess(param);
							} else {
								param.bendreq = true;
								param.bnetdata = true;
								sendMessage(NET_COMPLETE, param);
								if (param.activitybase != null) {
									// 在这里将从服务端拉取的数据存放到数据库中
									if(param.activitybase instanceof ActivityBase) {
										ActivityBase base = (ActivityBase) param.activitybase;
										CacheDataCtrl cacheDataCtrl = base.getZuZhiLiDBCtrl().getCacheDataCtrl();
										if(cacheDataCtrl != null) {
											cacheDataCtrl.insertRec(param);
											cacheDataCtrl.checkCache(param.cachetype);
										}
									}
								}
							}

						} else {
							Log.d("debug", "net server err:" + y);
							param.rstmsg = y;
							if (bissyncrst) {
								param.listener.onNetError(param);
							} else {

								sendMessage(NET_ERROR, param);
							}
							// sendMessage(NET_ERROR, param);
						}
					} catch (JSONException e) {
						Log.d("debug", "net server exp:" + e.getMessage());
						param.rstmsg = retBuf;
						if (bissyncrst) {
							param.listener.onNetError(param);
						} else {

							sendMessage(NET_ERROR, param);
						}
					}

					// String result[]=retBuf.split(";fenhao");
					// Matcher m = mpattern_err.matcher(result[0]);
					// if(m.find()){
					//
					//
					// }else
					// {
					// }

				} else {
					param.rstmsg = CommonDefine.getResources(param.ctx)
							.getString(R.string.neterr_message);
					if (bissyncrst) {
						param.listener.onNetError(param);
					} else {

						sendMessage(NET_ERROR, param);
					}
					// sendMessage(NET_ERROR, param);
				}
			} catch (ClientProtocolException e) {
				Log.d("debug", "net exp:" + e.getMessage());
				e.printStackTrace();
				param.rstmsg = CommonDefine.getResources(param.ctx).getString(
						R.string.neterr_message);
				if (bissyncrst) {
					param.listener.onNetError(param);
				} else {

					sendMessage(NET_ERROR, param);
				}
				// sendMessage(NET_ERROR, param);
			} catch (IOException e) {
				Log.d("debug", "net exp:" + e.getMessage());
				e.printStackTrace();
				param.rstmsg = CommonDefine.getResources(param.ctx).getString(
						R.string.neterr_message);
				if (bissyncrst) {
					param.listener.onNetError(param);
				} else {

					sendMessage(NET_ERROR, param);
				}
				// sendMessage(NET_ERROR, param);
			}

			httpRequest = null;
			httpResponse = null;
		} while (false);
		return bRet;

	}
	

	boolean cacheTask(HttpRequestParam param) {
		boolean b = false;
		String start = (String) param.nodesrequest.get("begin");
		if (start == null || !start.equals("0")) {
			return b;
		}
		CacheDataCtrl db = null;
		if(param.activitybase instanceof ActivityBase) {
			ActivityBase base = (ActivityBase) param.activitybase;
			db = base.getZuZhiLiDBCtrl().getCacheDataCtrl();
		}
		long time = db.getCacheTime(param.cachetype, param.identify);
		param.jsonstr = db.getCacheData(param.cachetype, param.identify);
		
		if ((System.currentTimeMillis() - time) > param.expiretime ) {
			
		}else{
			param.bendreq = true;
			b = true;
		}
		if (param.jsonstr != null) {
			param.bcachedata = true;
			sendMessage(NET_COMPLETE, param);
		}
		return b;
	}

	public void clearCache(ActivityBase src, int type, String identity) {
		CacheDataCtrl db = src.getZuZhiLiDBCtrl().getCacheDataCtrl();
		db.clearCache(type, identity);
	}

	void uploadTextParam(List<NameValuePair> params, MultipartEntity entity) {
		String key = "";
		try {
			for (int loc = 0; loc < params.size(); loc++) {
				key = params.get(loc).getName();
				StringBody tamp = new StringBody("");
				entity.addPart(key, new StringBody(params.get(loc).getValue(),
						Charset.forName("UTF-8")));
			}

		} catch (UnsupportedEncodingException e) {

		}

	}

	void uploadBinaryFileParam(
			Map<String, ByteArrayOutputStream> binaryfiles,
			MultipartEntity entity) {
		Iterator it = binaryfiles.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String key = (String) entry.getKey();
			entity.addPart(key, new ByteArrayBody(
					((ByteArrayOutputStream) entry.getValue()).toByteArray(),"temp.jpg"));
		}

	}
	
	void uploadAttatchFileParam(
			Map<String, Object> attatchfiles,
			MultipartEntity entity) {
		Iterator it = attatchfiles.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String key = (String) entry.getKey();
			Object value = entry.getValue();
			File file = null;
			byte [] bytes = null;
			if(value instanceof String) {
				file = new File((String) value);
				entity.addPart(key, new FileBody(file));
			} else if(value instanceof ByteArrayOutputStream) {
				bytes = ((ByteArrayOutputStream) value).toByteArray();
				entity.addPart(key, new ByteArrayBody(bytes, "temp.jpg"));
			}
		}
	}

	private void addParamsPost(List<NameValuePair> params,
			Map<String, Object> nodesrequest) {
		Iterator it = nodesrequest.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			params.add(new BasicNameValuePair((String) entry.getKey(),
					(String) entry.getValue()));
		}
	}

	private void normalParamsUpload(ByteArrayOutputStream bos,
			List<NameValuePair> params) {
		String key = "";
		for (int loc = 0; loc < params.size(); loc++) {
			key = params.get(loc).getName();
			StringBuilder temp = new StringBuilder(10);
			temp.setLength(0);
			temp.append(MP_BOUNDARY).append("\r\n");
			temp.append("content-disposition: form-data; name=\"").append(key)
					.append("\"\r\n\r\n");
			temp.append(params.get(loc).getValue()).append("\r\n");
			byte[] res = temp.toString().getBytes();
			try {
				bos.write(res);
			} catch (IOException e) {
				// throw new WeiboException(e);
			}
		}

	}

	private void binaryParamsUpload(ByteArrayOutputStream bos,
			Map<String, ByteArrayOutputStream> attatchfiles) {

		Iterator it = attatchfiles.entrySet().iterator();
		boolean bhavedata = false;
		while (it.hasNext()) {
			bhavedata = true;
			Map.Entry entry = (Map.Entry) it.next();
			String key = (String) entry.getKey();
			ByteArrayOutputStream bin = (ByteArrayOutputStream) entry
					.getValue();
			StringBuilder temp = new StringBuilder();

			temp.append(MP_BOUNDARY).append("\r\n");
			temp.append("Content-Disposition: form-data; name=\"" + key + "\";")
					.append("\r\n");
			String filetype = "application/octet-stream";
			temp.append("Content-Type: ").append(filetype).append("\r\n\r\n");
			byte[] res = temp.toString().getBytes();
			try {
				bos.write(res);
				bos.write(bin.toByteArray());
				// imgpath.compress(CompressFormat.PNG, 75, out);
				bos.write("\r\n".getBytes());
				bin.close();
			} catch (IOException e) {
				// throw new WeiboException(e);
			} finally {

			}
		}
		if (bhavedata) {

			try {
				bos.write(("\r\n" + END_MP_BOUNDARY).getBytes());
			} catch (IOException e) {
				// throw new WeiboException(e);
			} finally {

			}
		}

	}

	public static boolean CheckNetwork(Context ctx) {

		boolean flag = false;
		ConnectivityManager cwjManager = (ConnectivityManager) ctx
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cwjManager.getActiveNetworkInfo() != null)
			flag = cwjManager.getActiveNetworkInfo().isAvailable();
		if (!flag) {
			// final CustomDlg dlg = new CustomDlg(Splash.this,
			// R.style.mydialog);
			// dlg.setDisplayView( null,"网络连接失败，请检查网�"设置网络","退�
			// dlg.setLBtnListner(new View.OnClickListener() {
			// @Override
			// public void onClick(View arg0) {
			// dlg.cancel();
			// Intent mIntent = new Intent();
			// mIntent.setAction("android.settings.WIRELESS_SETTINGS");
			// startActivity(mIntent);
			// Splash.this.finish();
			// }
			// });
			//
			// dlg.setRBtnListner(new View.OnClickListener() {
			// @Override
			// public void onClick(View arg0) {
			// dlg.cancel();
			// Splash.this.finish();
			// }
			// });
			//
			// if(!this.isFinishing()) dlg.show();

		} else {

		}

		return flag;

	}

	private String getTestJson(String task) {
		String ret = "";
		if (SDCardAccessor.isSDCardAvailable()) {
			File fp = new File(SDCardAccessor.getTestJsonFullPath(task));

			try {
				FileReader fr = new FileReader(fp);
				BufferedReader textReader = new BufferedReader(fr);
				ret = textReader.readLine();

			} catch (Exception e) {
			}
		}

		return ret;
	}

	public void downloadFile(String url, DownloadListener DownloadListener,
			String filename) {
		mDownloadListener = DownloadListener;
		final String urltemp = url;
		final String filenametemp = filename;
		new Thread(new Runnable() {
			@Override
			public void run() {

				try {
					down_file(urltemp, "/sdcard/downloads/lucky/", filenametemp);
					// 濞戞挸顑堝ù鍥棘閸ワ附顐介柨娑樿嫰瀵剟寮敮顔剧獥缂佹鍏涚粩瀛樼▔閻氬摏L闁挎稑鐬奸鍥ㄧ鐏炲ジ鍤嬮悗娑櫳戦弬浣烘崉椤栨氨绐�
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}

	private void sendMessage(int what, Object obj) {
		Message msg = mHandler.obtainMessage(what, obj);
		mHandler.sendMessage(msg);
	}

	private void sendMessage(int what) {
		Message msg = mHandler.obtainMessage(what);
		mHandler.sendMessage(msg);
	}

	private void sendMessage(int what, int arg1, int arg2) {
		Message msg = mHandler.obtainMessage(what, arg1, arg2);
		mHandler.sendMessage(msg);
	}

	private void sendMessage(int what, int arg1) {
		Message msg = new Message();
		msg.arg1 = arg1;
		msg.what = what;
		mHandler.sendMessage(msg);
	}

	private class EventHandler extends Handler {
		private HttpHelperWraper mManager;

		public EventHandler() {
		}

		// 濠㈣泛瀚幃濠囧箳閵夛附鏆柛鎺撳濞堟垵鈽夐崼鐔剁礀
		@Override
		public void handleMessage(Message msg) {
			HttpRequestParam temp = (HttpRequestParam) msg.obj;
			if (temp.listener == null) {
				Log.v("liu", "temp.listener == null");
				return;
			}
			// liutao
			String listenerName = temp.listener.getClass().getName();
			Log.i("liu", "listenerName: " + listenerName);
			switch (msg.what) {

			case NET_COMPLETE:
				temp.listener.onNetSuccess(temp);
				break;
			case NET_ERROR:
				temp.listener.onNetError(temp);
				break;
			case DOWN_BEGIN:
				if (mDownloadListener != null)
					mDownloadListener.onDownloadBegin(msg.arg1);
				break;
			case DOWN_UPDATE_PROGRESS:
				if (mDownloadListener != null)
					mDownloadListener.onDownloadUpdateProgress(msg.arg1);
				break;
			case DOWN_END:
				if (mDownloadListener != null)
					mDownloadListener.onDownloadEnd((String) msg.obj);
				break;
			default:
				break;
			}
		}
	}

	public static class NetworkControl {

		/**
		 * 闁告帇鍊栭弻鍥亹閹惧啿顤呯紓鍐╁灩缁爼鎮╅懜纰夋嫹闁哄嫷鍨伴幆渚�矗椤栨粍鏆�
		 * 
		 * @param context
		 * @return
		 */
		public boolean getNetworkState(Context context) {
			ConnectivityManager connectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo info = connectivityManager.getActiveNetworkInfo();

			if (info != null) {
				return true;
			}

			return false;
		}

		/**
		 * 闁告帇鍊栭弻鍥╃磾閹寸姷鎹曠紒顐ヮ嚙閿燂�
		 * 
		 * @param context
		 * @return
		 */
		public static NetType getNetType(Context context) {
			ConnectivityManager connectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivityManager == null)
				return null;

			NetworkInfo info = connectivityManager.getActiveNetworkInfo();
			if (info == null)
				return null;

			String type = info.getTypeName();

			if (type.equalsIgnoreCase("WIFI")) {
				// WIFI闁哄倻鎳撻敓锟� return null;
			} else if (type.equalsIgnoreCase("MOBILE")) {
				// GPRS闁哄倻鎳撻敓锟�
				String proxyHost = android.net.Proxy.getDefaultHost();
				if (proxyHost != null && !proxyHost.equals("")) {
					// WAP闁哄倻鎳撻敓锟�
					NetType netType = new NetType();
					netType.setProxy(proxyHost);
					netType.setPort(android.net.Proxy.getDefaultPort());
					netType.setWap(true);
					return netType;
				}
			}
			return null;
		}

		public static class NetType {
			private String apn = "";
			private String proxy = "";
			private String typeName = "";
			private int port = 0;
			private boolean isWap = false;

			public String getApn() {
				return apn;
			}

			public void setApn(String apn) {
				this.apn = apn;
			}

			public int getPort() {
				return port;
			}

			public void setPort(int port) {
				this.port = port;
			}

			public String getProxy() {
				return proxy;
			}

			public void setProxy(String proxy) {
				this.proxy = proxy;
			}

			public boolean isWap() {
				return isWap;
			}

			public void setWap(boolean isWap) {
				this.isWap = isWap;
			}

			public String getTypeName() {
				return typeName;
			}

			public void setTypeName(String typeName) {
				this.typeName = typeName;
			}
		}

	}

	public void down_file(String url, String path, String filenameOuter)
			throws IOException {
		// 濞戞挸顑堝ù鍥礄閼恒儲娈�
		File f = new File(path);
		f.mkdirs();
		String filename = null;
		if (filenameOuter == null) {

			filename = url.substring(url.lastIndexOf("=") + 1);
		} else {
			filename = filenameOuter;
		}
		// 闁兼儳鍢茶ぐ鍥棘閸ワ附顐介柛姘炬嫹
		URL myURL = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
		// conn.connect();
		InputStream is = conn.getInputStream();
		int fileSize = conn.getContentLength();// 闁哄秷顬冨畵渚�传瀹ュ懐瀹夐柤鎯у槻瑜板洭寮崶锔筋偨濠㈠爢鍐瘓
		if (fileSize <= 0)
			throw new RuntimeException("file size excepting");
		if (is == null)
			throw new RuntimeException("stream is null");
		String SDFilePath = path + filename;

		// f.createNewFile();
		FileOutputStream fos = new FileOutputStream(new File(SDFilePath));
		// 闁硅泛锕ラ弳鐔煎箲椤旇偐鎽犻柛蹇嬪劥閻儳顕ラ敓浠嬪棘閸ワ附顐介柛姘炬嫹
		byte buf[] = new byte[128];
		int downLoadFileSize = 0;
		sendMessage(DOWN_BEGIN, fileSize);
		do {
			// 鐎甸偊浜為獮鍡欐嫚鐠囨彃绲�
			int numread = is.read(buf);
			if (numread == -1) {
				break;
			}
			fos.write(buf, 0, numread);
			downLoadFileSize += numread;

			sendMessage(DOWN_UPDATE_PROGRESS, downLoadFileSize);// 闁哄洤鐡ㄩ弻濠冩交濞戞ê顔婇柡澶涙�
		} while (true);

		try {
			is.close();
			fos.close();
			sendMessage(DOWN_END, SDFilePath);// 闂侇偅姘ㄩ悡鈩冪▔鐎ｎ厽绁伴悗鐟版湰閿燂�
		} catch (Exception ex) {
			Log.e("tag", "error: " + ex.getMessage(), ex);
		}
		conn.disconnect();
	}

}
